//
//  downLoad.m
//  testDownLoad
//
//  Created by 徐海宇 on 16/3/3.
//  Copyright © 2016年 徐海宇. All rights reserved.
//

#import "downLoad.h"

#import "InSound.h"

#import "InDownLoadSound.h"

@interface downLoad ()<NSURLConnectionDataDelegate>

@property (nonatomic,strong)NSFileHandle *writeHandle;

@property (nonatomic,assign)long long totalLength;

@property (nonatomic,assign)long long currentLength;

@property (nonatomic,strong)NSURLConnection *connection;


@end

@implementation downLoad

#pragma mark - NSURLConnectionDataDelegate代理方法
//请求失败时调用（请求超时、网络异常）

//@param error      错误原因

- (void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error {
    
    NSLog(@"didFailWithError");
    
}

/**
 *  1.接收到服务器的响应就会调用
 *
 *  @param response   响应
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
    if (self.currentLength) return;
    
    //文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString *filePath = [caches stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",self.insound.sound_id]];
    
//    self.insound.inSound_Url = filePath;
    
    NSLog(@"%@",caches);
    NSLog(@"path   %@",filePath);
    //创建一个空的文件 到沙盒中
    NSFileManager *manager = [NSFileManager defaultManager];
    
    [manager createFileAtPath:filePath contents:nil attributes:nil];
    
    
    //创建一个用来写数据的文件句柄
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    
    
    //获得文件的总大小
    self.totalLength = response.expectedContentLength;
    
}

/**
 *  2.当接收到服务器返回的实体数据时调用（具体内容，这个方法可能会被^调用多次）
 *
 *  @param data       这次返回的数据
 */
- (void)connection:(NSConnection *)connection didReceiveData:(nonnull NSData *)data {
    //移动到文件的最后面
    [self.writeHandle seekToEndOfFile];
    
    //将数据写入沙盒
    [self.writeHandle writeData:data];
    
    //累计文件 的长度
    self.currentLength += data.length;
    
    
}

/**
 *  3.加载完毕后调用（服务器的数据已经完全返回后）
 */

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    self.currentLength = 0;
    self.totalLength = 0;
    
    //关闭文件
    [self.writeHandle closeFile];
    self.writeHandle = nil;
    
    
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString *filePath = [caches stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",self.insound.sound_id]];
    
    self.insound.inSound_Url = [NSString stringWithFormat:@"file://%@",filePath];

   BOOL isDownLoad = [InDownLoadSound insertInToSound:self.insound];
    
    
    NSLog(@"%d",isDownLoad);
//    if (isDownLoad) {
        NSArray *array = [InDownLoadSound soundArray];
        InSound *sound = array[0];
        NSLog(@" sound Url  %@",sound.inSound_Url);
 //   }

    
    NSLog(@"11111");
    
}

//返回文件路径
//- (NSString *)soundPath {
//    
//    return self.soundPath;
//
//}



- (void)downLoadWithInSound:(InSound *)inSound{
    
    self.insound = inSound;
    
    NSURL *url = [NSURL URLWithString:inSound.inSound_Url];
    //2 请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //设置请求头 告诉服务器从哪里开始下载  实现断点续传
    NSString *range = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
    
    //文件的分段字节范围
    [request setValue:range forHTTPHeaderField:@"Range"];
    
    // 3 下载 （创建完conn对象后 会自动发起一个异步请求）
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    
   // NSLog(@" sound Path%@",self.soundPath);
    
}

@end
